package com.lisx.module_add_new_word.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyPaintView extends View {

    private List<Point> allPoints = new ArrayList<Point>();

    //接受context以及属性集合(宽度，高度等)
    public MyPaintView(Context context, AttributeSet attrs) {
        super(context, attrs);
        super.setOnTouchListener(new OnTouchListenerImp());
        init();
    }

    private void init() {
        //依靠此类开始画线

    }

    private class OnTouchListenerImp implements OnTouchListener {

        public boolean onTouch(View v, MotionEvent event) {
            Point p = new Point((int) event.getX(), (int) event.getY());
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //用户按下，表示重新开始保存点
                allPoints = new ArrayList<Point>();
                allPoints.add(p);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                //用户松开
                allPoints.add(p);
                postInvalidate();//重绘图像
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                allPoints.add(p);
                postInvalidate();//重绘图像
            }
            return true;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint p = new Paint();
        p.setColor(Color.BLACK);
        p.setStrokeCap(Paint.Cap.ROUND);
        p.setAntiAlias(true);
        p.setStrokeWidth(15);
        p.setStyle(Paint.Style.STROKE);
        if (allPoints.size() > 1) {
            //如果有坐标点，开始绘图
            Iterator<Point> iter = allPoints.iterator();
            Point first = null;
            Point last = null;
            while (iter.hasNext()) {
                if (first == null) {
                    first = (Point) iter.next();
                } else {
                    if (last != null) {
                        first = last;
                    }
                    last = (Point) iter.next();//结束
                    canvas.drawLine(first.x, first.y, last.x, last.y, p);
                }
            }
        }
    }

    public void cleanPoints(){
        allPoints.clear();
        invalidate();
    }
}
